from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from multiprocess import Lock
import sys,os,pymysql
from fabric.api import *

lock=Lock()
class ConMySQL():
    def __init__(self, host='127.0.0.1', user='root', passwd='', db='dist'):
        try:
            #self.con = pymysql.connect(host='127.0.0.1', db='dist', charset='utf8mb4')
            #self.con = pymysql.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db, charset='utf8mb4')
            self.con = pymysql.connect(host=host, user=user, passwd=passwd, db=db, charset='utf8mb4')
        except Exception as e:
            msg = "\033[31;1mError:Can't connect,{}".format(e.args[1])
            print(msg)
            os._exit(0)
        self.cursor = self.con.cursor()
    def query_string(self, sql):
        lock.acquire()
        self.cursor.execute(sql)
        lock.release()
        return self.cursor.fetchall()[0][0]
    # 返回值为2元tuple
    def query_tuple(self, sql):
        lock.acquire()
        self.cursor.execute(sql)
        lock.release()
        return self.cursor.fetchall()
    # 返回值为2元tuple中的第一个元素，仍为tuple
    def query_tuple_one(self, sql):
        lock.acquire()
        self.cursor.execute(sql)
        lock.release()
        return self.cursor.fetchall()[0]
    def query_insert(self, sql):
        lock.acquire()
        self.cursor.execute(sql)
        lock.release()
        return self.cursor.fetchall()

mysql=ConMySQL()


# Create your views here.
def login(request):
	#if request.method == 'GET':
	#	next = request.GET.get('next')
#		print(next,'---------------')
#		if next is None:
#			next = '/clean'
#		return render(request,'login.html')
	request.method == "POST"
	username = request.POST.get('user',None)
	password = request.POST.get('pwd',None)
	#next = request.POST.get('next')
	#print('next:',next)
	user = auth.authenticate(username=username,password=password)
	if user is not None and user.is_active:
		auth.login(request,user)
		return redirect('qianyi/')
	else:
		err_msg="用户名或密码错误"
	return render(request,'login.html')

def get_game():
	game_list=mysql.query_tuple('select cn_name from game where is_online=1 and game_type=0')
	a=[]
	for i in game_list:
		a.append(i[0])
	return a




@login_required
def qianyi(request):
	game_list=get_game
	#print(game_list)
	return render(request,'qianyi.html',locals())
